<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>overload - Package for overloading Perl operations - Perldoc Browser</title>
    <link rel="search" href="https://perldoc.perl.org/opensearch.xml" type="application/opensearchdescription+xml" title="Perldoc Browser">
    <link rel="canonical" href="https://perldoc.perl.org/overload">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/10.5.0/styles/stackoverflow-light.min.css" integrity="sha512-cG1IdFxqipi3gqLmksLtuk13C+hBa57a6zpWxMeoY3Q9O6ooFxq50DayCdm0QrDgZjMUn23z/0PMZlgft7Yp5Q==" crossorigin="anonymous" />
    <style>
      body {
        background: #f4f4f5;
        color: #020202;
      }
      .navbar-dark {
        background-image: -webkit-linear-gradient(top, #005f85 0, #002e49 100%);
        background-image: -o-linear-gradient(top, #005f85 0, #002e49 100%);
        background-image: linear-gradient(to bottom, #005f85 0, #002e49 100%);
        filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff005f85', endColorstr='#ff002e49', GradientType=0);
        background-repeat: repeat-x;
      }
      .navbar-dark .navbar-nav .nav-link,
      .navbar-dark .navbar-nav .nav-link:focus { color: #fff }
      .navbar-dark .navbar-nav .nav-link:hover { color: #ffef68 }
      #wrapperlicious {
        margin: 0 auto;
        font: 0.9em 'Helvetica Neue', Helvetica, sans-serif;
        font-weight: normal;
        line-height: 1.5em;
        margin: 0;
        padding: 0;
      }
      #wrapperlicious h1 { font-size: 1.5em }
      #wrapperlicious h2 { font-size: 1.3em }
      #wrapperlicious h3 { font-size: 1.1em }
      #wrapperlicious h4 { font-size: 0.9em }
      #wrapperlicious h1, #wrapperlicious h2, #wrapperlicious h3,
      #wrapperlicious h4, #wrapperlicious dt {
        color: #020202;
        margin-top: 1em;
        margin-bottom: 1em;
        position: relative;
        font-weight: bold;
      }
      #wrapperlicious a { color: inherit; text-decoration: underline }
      #wrapperlicious #toc { text-decoration: none }
      #wrapperlicious a:hover { color: #2a2a2a }
      #wrapperlicious a img { border: 0 }
      #wrapperlicious :not(pre) > code {
        color: inherit;
        background-color: rgba(0, 0, 0, 0.04);
        border-radius: 3px;
        font: 0.9em Consolas, Menlo, Monaco, monospace;
        padding: 0.3em;
      }
      #wrapperlicious dd {
        margin: 0;
        margin-left: 2em;
      }
      #wrapperlicious dt {
        color: #2a2a2a;
        font-weight: bold;
        margin-left: 0.9em;
      }
      #wrapperlicious p {
        margin-bottom: 1em;
        margin-top: 1em;
      }
      #wrapperlicious li > p {
        margin-bottom: 0;
        margin-top: 0;
      }
      #wrapperlicious pre {
        border: 1px solid #c1c1c1;
        border-radius: 3px;
        font: 100% Consolas, Menlo, Monaco, monospace;
        margin-bottom: 1em;
        margin-top: 1em;
      }
      #wrapperlicious pre > code {
        display: block;
        background-color: #f6f6f6;
        font: 0.9em Consolas, Menlo, Monaco, monospace;
        line-height: 1.5em;
        text-align: left;
        white-space: pre;
        padding: 1em;
      }
      #wrapperlicious dl, #wrapperlicious ol, #wrapperlicious ul {
        margin-bottom: 1em;
        margin-top: 1em;
      }
      #wrapperlicious ul {
        list-style-type: square;
      }
      #wrapperlicious ul ul {
        margin-bottom: 0px;
        margin-top: 0px;
      }
      #footer {
        font-size: 0.8em;
        padding-top: 0.5em;
        text-align: center;
      }
      #more {
        display: inline;
        font-size: 0.8em;
      }
      #perldocdiv {
        background-color: #fff;
        border: 1px solid #c1c1c1;
        border-bottom-left-radius: 5px;
        border-bottom-right-radius: 5px;
        margin-left: auto;
        margin-right: auto;
        padding: 3em;
        padding-top: 1em;
        max-width: 960px;
      }
      #moduleversion { float: right }
      #wrapperlicious .leading-notice {
        font-style: italic;
        padding-left: 1em;
        margin-top: 1em;
        margin-bottom: 1em;
      }
      #wrapperlicious .permalink {
        display: none;
        left: -0.75em;
        position: absolute;
        padding-right: 0.25em;
        text-decoration: none;
      }
      #wrapperlicious h1:hover .permalink, #wrapperlicious h2:hover .permalink,
      #wrapperlicious h3:hover .permalink, #wrapperlicious h4:hover .permalink,
      #wrapperlicious dt:hover .permalink {
        display: block;
      }
    </style>
    <!-- Global site tag (gtag.js) - Google Analytics -->
    <script async src="https://www.googletagmanager.com/gtag/js?id=G-KVNWBNT5FB"></script>
    <script>
      window.dataLayer = window.dataLayer || [];
      function gtag(){dataLayer.push(arguments);}
      gtag('js', new Date());

      gtag('config', 'G-KVNWBNT5FB');
      gtag('config', 'UA-50555-3');
    </script>
  </head>
  <body>
    <nav class="navbar navbar-expand-md navbar-dark bg-dark justify-content-between">
  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
    <span class="navbar-toggler-icon"></span>
  </button>
  <a class="navbar-brand" href="https://perldoc.perl.org/">Perldoc Browser</a>
  <div class="collapse navbar-collapse" id="navbarNav">
    <ul class="navbar-nav mr-auto">
      <li class="nav-item dropdown text-nowrap">
        <a class="nav-link dropdown-toggle" href="overload.html#" id="dropdownlink-stable" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">5.35.0</a>
        <div class="dropdown-menu" aria-labelledby="dropdownlink-stable">
          <a class="dropdown-item" href="https://perldoc.perl.org/overload">Latest</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.38.2/overload">5.38.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.38.1/overload">5.38.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.38.0/overload">5.38.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.36.3/overload">5.36.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.36.2/overload">5.36.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.36.1/overload">5.36.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.36.0/overload">5.36.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.34.3/overload">5.34.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.34.2/overload">5.34.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.34.1/overload">5.34.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.34.0/overload">5.34.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.32.1/overload">5.32.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.32.0/overload">5.32.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.30.3/overload">5.30.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.30.2/overload">5.30.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.30.1/overload">5.30.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.30.0/overload">5.30.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.28.3/overload">5.28.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.28.2/overload">5.28.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.28.1/overload">5.28.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.28.0/overload">5.28.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.26.3/overload">5.26.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.26.2/overload">5.26.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.26.1/overload">5.26.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.26.0/overload">5.26.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.24.4/overload">5.24.4</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.24.3/overload">5.24.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.24.2/overload">5.24.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.24.1/overload">5.24.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.24.0/overload">5.24.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.22.4/overload">5.22.4</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.22.3/overload">5.22.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.22.2/overload">5.22.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.22.1/overload">5.22.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.22.0/overload">5.22.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.20.3/overload">5.20.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.20.2/overload">5.20.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.20.1/overload">5.20.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.20.0/overload">5.20.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.18.4/overload">5.18.4</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.18.3/overload">5.18.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.18.2/overload">5.18.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.18.1/overload">5.18.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.18.0/overload">5.18.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.16.3/overload">5.16.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.16.2/overload">5.16.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.16.1/overload">5.16.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.16.0/overload">5.16.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.14.4/overload">5.14.4</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.14.3/overload">5.14.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.14.2/overload">5.14.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.14.1/overload">5.14.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.14.0/overload">5.14.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.12.5/overload">5.12.5</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.12.4/overload">5.12.4</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.12.3/overload">5.12.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.12.2/overload">5.12.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.12.1/overload">5.12.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.12.0/overload">5.12.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.10.1/overload">5.10.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.10.0/overload">5.10.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.8.9/overload">5.8.9</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.8.8/overload">5.8.8</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.8.7/overload">5.8.7</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.8.6/overload">5.8.6</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.8.5/overload">5.8.5</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.8.4/overload">5.8.4</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.8.3/overload">5.8.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.8.2/overload">5.8.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.8.1/overload">5.8.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.8.0/overload">5.8.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.6.2/overload">5.6.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.6.1/overload">5.6.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.6.0/overload">5.6.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.005_04/overload">5.005_04</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.005_03/overload">5.005_03</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.005_02/overload">5.005_02</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.005_01/overload">5.005_01</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.005/overload">5.005</a>
        </div>
      </li>
      <li class="nav-item dropdown text-nowrap">
        <a class="nav-link dropdown-toggle" href="overload.html#" id="dropdownlink-dev" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Dev</a>
        <div class="dropdown-menu" aria-labelledby="dropdownlink-dev">
          <a class="dropdown-item" href="https://perldoc.perl.org/blead/overload">blead</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.39.6/overload">5.39.6</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.39.5/overload">5.39.5</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.39.4/overload">5.39.4</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.39.3/overload">5.39.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.39.2/overload">5.39.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.39.1/overload">5.39.1</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.38.0-RC2/overload">5.38.0-RC2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.38.0-RC1/overload">5.38.0-RC1</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.37.11/overload">5.37.11</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.37.10/overload">5.37.10</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.37.9/overload">5.37.9</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.37.8/overload">5.37.8</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.37.7/overload">5.37.7</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.37.6/overload">5.37.6</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.37.5/overload">5.37.5</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.37.4/overload">5.37.4</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.37.3/overload">5.37.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.37.2/overload">5.37.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.37.1/overload">5.37.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.37.0/overload">5.37.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.35.11/overload">5.35.11</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.35.10/overload">5.35.10</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.35.9/overload">5.35.9</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.35.8/overload">5.35.8</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.35.7/overload">5.35.7</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.35.6/overload">5.35.6</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.35.5/overload">5.35.5</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.35.4/overload">5.35.4</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.35.3/overload">5.35.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.35.2/overload">5.35.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.35.1/overload">5.35.1</a>
          <a class="dropdown-item active" href="overload.html">5.35.0</a>
        </div>
      </li>
      <li class="nav-item dropdown text-nowrap">
        <a class="nav-link dropdown-toggle" href="overload.html#" id="dropdownlink-nav" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Documentation</a>
        <div class="dropdown-menu" aria-labelledby="dropdownlink-nav">
          <a class="dropdown-item" href="perl.html">Perl</a>
          <a class="dropdown-item" href="perlintro.html">Intro</a>
          <a class="dropdown-item" href="perl.html#Tutorials">Tutorials</a>
          <a class="dropdown-item" href="perlfaq.html">FAQs</a>
          <a class="dropdown-item" href="perl.html#Reference-Manual">Reference</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="perlop.html">Operators</a>
          <a class="dropdown-item" href="functions.html">Functions</a>
          <a class="dropdown-item" href="variables.html">Variables</a>
          <a class="dropdown-item" href="modules.html">Modules</a>
          <a class="dropdown-item" href="perlutil.html">Utilities</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="perlcommunity.html">Community</a>
          <a class="dropdown-item" href="perlhist.html">History</a>
        </div>
      </li>
    </ul>
    <ul class="navbar-nav">
      <script>
        function set_expand (expand) {
          var perldocdiv = document.getElementById('perldocdiv');
          var width = window.getComputedStyle(perldocdiv).getPropertyValue('max-width');
          var expanded = (width == '' || width == 'none') ? true : false;
          if (expand === null) {
            expand = !expanded;
          }
          if ((expand && !expanded) || (!expand && expanded)) {
            perldocdiv.style.setProperty('max-width', expand ? 'none' : '960px');
            var button_classlist = document.getElementById('content-expand-button').classList;
            if (expand) {
              button_classlist.add('btn-light');
              button_classlist.remove('btn-outline-light');
            } else {
              button_classlist.add('btn-outline-light');
              button_classlist.remove('btn-light');
            }
          }
          return expand;
        }
        function toggle_expand () {
          var expand = set_expand(null);
          document.cookie = 'perldoc_expand=' + (expand ? 1 : 0) + '; path=/; expires=Tue, 19 Jan 2038 03:14:07 UTC';
        }
        function read_expand () {
          return document.cookie.split(';').some(function (item) { return item.indexOf('perldoc_expand=1') >= 0 });
        }
        if (document.readyState === 'loading') {
          document.addEventListener('DOMContentLoaded', function () {
            if (read_expand()) {
              set_expand(true);
            }
          });
        } else if (read_expand()) {
          set_expand(true);
        }
      </script>
      <button id="content-expand-button" type="button" class="btn btn-outline-light d-none d-lg-inline-block mr-2" onclick="toggle_expand()">Expand</button>
    <ul>
    <form class="form-inline" method="get" action="https://perldoc.perl.org/5.35.0/search">
      <input class="form-control mr-3" type="search" name="q" placeholder="Search" aria-label="Search">
    </form>
  </div>
</nav>

    <div id="wrapperlicious" class="container-fluid">
      <div id="perldocdiv">
        <div id="links">
          <a href="overload.html">overload</a>
          <div id="more">
            (<a href="overload.txt">source</a>,
            <a href="https://metacpan.org/pod/overload">CPAN</a>)
          </div>
            <div id="moduleversion">version 1.33</div>
        </div>
        <div class="leading-notice">
          You are viewing the version of this documentation from Perl 5.35.0.
            This is a development version of Perl.
        </div>
        <h1><a id="toc">CONTENTS</a></h1>
                  <ul>
              <li>
                <a class="text-decoration-none" href="overload.html#NAME">NAME</a>
              </li>
              <li>
                <a class="text-decoration-none" href="overload.html#SYNOPSIS">SYNOPSIS</a>
              </li>
              <li>
                <a class="text-decoration-none" href="overload.html#DESCRIPTION">DESCRIPTION</a>
                            <ul>
              <li>
                <a class="text-decoration-none" href="overload.html#Fundamentals">Fundamentals</a>
                            <ul>
              <li>
                <a class="text-decoration-none" href="overload.html#Declaration">Declaration</a>
              </li>
              <li>
                <a class="text-decoration-none" href="overload.html#Calling-Conventions-and-Magic-Autogeneration">Calling Conventions and Magic Autogeneration</a>
              </li>
              <li>
                <a class="text-decoration-none" href="overload.html#Mathemagic,-Mutators,-and-Copy-Constructors">Mathemagic, Mutators, and Copy Constructors</a>
              </li>
          </ul>

              </li>
              <li>
                <a class="text-decoration-none" href="overload.html#Overloadable-Operations">Overloadable Operations</a>
              </li>
              <li>
                <a class="text-decoration-none" href="overload.html#Magic-Autogeneration">Magic Autogeneration</a>
                            <ul>
              <li>
                <a class="text-decoration-none" href="overload.html#Minimal-Set-of-Overloaded-Operations">Minimal Set of Overloaded Operations</a>
              </li>
          </ul>

              </li>
              <li>
                <a class="text-decoration-none" href="overload.html#Special-Keys-for-use-overload">Special Keys for use overload</a>
                            <ul>
              <li>
                <a class="text-decoration-none" href="overload.html#nomethod">nomethod</a>
              </li>
              <li>
                <a class="text-decoration-none" href="overload.html#fallback">fallback</a>
              </li>
              <li>
                <a class="text-decoration-none" href="overload.html#Copy-Constructor">Copy Constructor</a>
              </li>
          </ul>

              </li>
              <li>
                <a class="text-decoration-none" href="overload.html#How-Perl-Chooses-an-Operator-Implementation">How Perl Chooses an Operator Implementation</a>
              </li>
              <li>
                <a class="text-decoration-none" href="overload.html#Losing-Overloading">Losing Overloading</a>
              </li>
              <li>
                <a class="text-decoration-none" href="overload.html#Inheritance-and-Overloading">Inheritance and Overloading</a>
              </li>
              <li>
                <a class="text-decoration-none" href="overload.html#Run-time-Overloading">Run-time Overloading</a>
              </li>
              <li>
                <a class="text-decoration-none" href="overload.html#Public-Functions">Public Functions</a>
              </li>
              <li>
                <a class="text-decoration-none" href="overload.html#Overloading-Constants">Overloading Constants</a>
              </li>
          </ul>

              </li>
              <li>
                <a class="text-decoration-none" href="overload.html#IMPLEMENTATION">IMPLEMENTATION</a>
              </li>
              <li>
                <a class="text-decoration-none" href="overload.html#COOKBOOK">COOKBOOK</a>
                            <ul>
              <li>
                <a class="text-decoration-none" href="overload.html#Two-face-Scalars">Two-face Scalars</a>
              </li>
              <li>
                <a class="text-decoration-none" href="overload.html#Two-face-References">Two-face References</a>
              </li>
              <li>
                <a class="text-decoration-none" href="overload.html#Symbolic-Calculator">Symbolic Calculator</a>
              </li>
              <li>
                <a class="text-decoration-none" href="overload.html#Really-Symbolic-Calculator">Really Symbolic Calculator</a>
              </li>
          </ul>

              </li>
              <li>
                <a class="text-decoration-none" href="overload.html#AUTHOR">AUTHOR</a>
              </li>
              <li>
                <a class="text-decoration-none" href="overload.html#SEE-ALSO">SEE ALSO</a>
              </li>
              <li>
                <a class="text-decoration-none" href="overload.html#DIAGNOSTICS">DIAGNOSTICS</a>
              </li>
              <li>
                <a class="text-decoration-none" href="overload.html#BUGS-AND-PITFALLS">BUGS AND PITFALLS</a>
              </li>
          </ul>

      <h1 id="NAME"><a class="permalink" href="overload.html#NAME">#</a>NAME</h1>

<p>overload - Package for overloading Perl operations</p>

<h1 id="SYNOPSIS"><a class="permalink" href="overload.html#SYNOPSIS">#</a>SYNOPSIS</h1>

<pre><code>    package SomeThing;

    use overload
	&#39;+&#39; =&gt; \&amp;myadd,
	&#39;-&#39; =&gt; \&amp;mysub;
	# etc
    ...

    package main;
    $a = SomeThing-&gt;new( 57 );
    $b = 5 + $a;
    ...
    if (overload::Overloaded $b) {...}
    ...
    $strval = overload::StrVal $b;</code></pre>

<h1 id="DESCRIPTION"><a class="permalink" href="overload.html#DESCRIPTION">#</a>DESCRIPTION</h1>

<p>This pragma allows overloading of Perl&#39;s operators for a class. To overload built-in functions, see <a href="perlsub.html#Overriding-Built-in-Functions">&quot;Overriding Built-in Functions&quot; in perlsub</a> instead.</p>

<h2 id="Fundamentals"><a class="permalink" href="overload.html#Fundamentals">#</a>Fundamentals</h2>

<h3 id="Declaration"><a class="permalink" href="overload.html#Declaration">#</a>Declaration</h3>

<p>Arguments of the <code>use overload</code> directive are (key, value) pairs. For the full set of legal keys, see <a href="overload.html#Overloadable-Operations">&quot;Overloadable Operations&quot;</a> below.</p>

<p>Operator implementations (the values) can be subroutines, references to subroutines, or anonymous subroutines - in other words, anything legal inside a <code>&amp;{ ... }</code> call. Values specified as strings are interpreted as method names. Thus</p>

<pre><code>package Number;
use overload
    &quot;-&quot; =&gt; &quot;minus&quot;,
    &quot;*=&quot; =&gt; \&amp;muas,
    &#39;&quot;&quot;&#39; =&gt; sub { ...; };</code></pre>

<p>declares that subtraction is to be implemented by method <code>minus()</code> in the class <code>Number</code> (or one of its base classes), and that the function <code>Number::muas()</code> is to be used for the assignment form of multiplication, <code>*=</code>. It also defines an anonymous subroutine to implement stringification: this is called whenever an object blessed into the package <code>Number</code> is used in a string context (this subroutine might, for example, return the number as a Roman numeral).</p>

<h3 id="Calling-Conventions-and-Magic-Autogeneration"><a class="permalink" href="overload.html#Calling-Conventions-and-Magic-Autogeneration">#</a><a id="Calling"></a>Calling Conventions and Magic Autogeneration</h3>

<p>The following sample implementation of <code>minus()</code> (which assumes that <code>Number</code> objects are simply blessed references to scalars) illustrates the calling conventions:</p>

<pre><code>package Number;
sub minus {
    my ($self, $other, $swap) = @_;
    my $result = $$self - $other;         # *
    $result = -$result if $swap;
    ref $result ? $result : bless \$result;
}
# * may recurse once - see table below</code></pre>

<p>Three arguments are passed to all subroutines specified in the <code>use overload</code> directive (with exceptions - see below, particularly <a href="overload.html#nomethod">&quot;nomethod&quot;</a>).</p>

<p>The first of these is the operand providing the overloaded operator implementation - in this case, the object whose <code>minus()</code> method is being called.</p>

<p>The second argument is the other operand, or <code>undef</code> in the case of a unary operator.</p>

<p>The third argument is set to TRUE if (and only if) the two operands have been swapped. Perl may do this to ensure that the first argument (<code>$self</code>) is an object implementing the overloaded operation, in line with general object calling conventions. For example, if <code>$x</code> and <code>$y</code> are <code>Number</code>s:</p>

<pre><code>operation   |   generates a call to
============|======================
$x - $y     |   minus($x, $y, &#39;&#39;)
$x - 7      |   minus($x, 7, &#39;&#39;)
7 - $x      |   minus($x, 7, 1)</code></pre>

<p>Perl may also use <code>minus()</code> to implement other operators which have not been specified in the <code>use overload</code> directive, according to the rules for <a href="overload.html#Magic-Autogeneration">&quot;Magic Autogeneration&quot;</a> described later. For example, the <code>use overload</code> above declared no subroutine for any of the operators <code>--</code>, <code>neg</code> (the overload key for unary minus), or <code>-=</code>. Thus</p>

<pre><code>operation   |   generates a call to
============|======================
-$x         |   minus($x, 0, 1)
$x--        |   minus($x, 1, undef)
$x -= 3     |   minus($x, 3, undef)</code></pre>

<p>Note the <code>undef</code>s: where autogeneration results in the method for a standard operator which does not change either of its operands, such as <code>-</code>, being used to implement an operator which changes the operand (&quot;mutators&quot;: here, <code>--</code> and <code>-=</code>), Perl passes undef as the third argument. This still evaluates as FALSE, consistent with the fact that the operands have not been swapped, but gives the subroutine a chance to alter its behaviour in these cases.</p>

<p>In all the above examples, <code>minus()</code> is required only to return the result of the subtraction: Perl takes care of the assignment to $x. In fact, such methods should <i>not</i> modify their operands, even if <code>undef</code> is passed as the third argument (see <a href="overload.html#Overloadable-Operations">&quot;Overloadable Operations&quot;</a>).</p>

<p>The same is not true of implementations of <code>++</code> and <code>--</code>: these are expected to modify their operand. An appropriate implementation of <code>--</code> might look like</p>

<pre><code>use overload &#39;--&#39; =&gt; &quot;decr&quot;,
    # ...
sub decr { --${$_[0]}; }</code></pre>

<p>If the &quot;bitwise&quot; feature is enabled (see <a href="feature.html">feature</a>), a fifth TRUE argument is passed to subroutines handling <code>&amp;</code>, <code>|</code>, <code>^</code> and <code>~</code>. This indicates that the caller is expecting numeric behaviour. The fourth argument will be <code>undef</code>, as that position (<code>$_[3]</code>) is reserved for use by <a href="overload.html#nomethod">&quot;nomethod&quot;</a>.</p>

<h3 id="Mathemagic,-Mutators,-and-Copy-Constructors"><a class="permalink" href="overload.html#Mathemagic,-Mutators,-and-Copy-Constructors">#</a><a id="Mathemagic"></a><a id="Mathemagic-Mutators-and-Copy-Constructors"></a>Mathemagic, Mutators, and Copy Constructors</h3>

<p>The term &#39;mathemagic&#39; describes the overloaded implementation of mathematical operators. Mathemagical operations raise an issue. Consider the code:</p>

<pre><code>$a = $b;
--$a;</code></pre>

<p>If <code>$a</code> and <code>$b</code> are scalars then after these statements</p>

<pre><code>$a == $b - 1</code></pre>

<p>An object, however, is a reference to blessed data, so if <code>$a</code> and <code>$b</code> are objects then the assignment <code>$a = $b</code> copies only the reference, leaving <code>$a</code> and <code>$b</code> referring to the same object data. One might therefore expect the operation <code>--$a</code> to decrement <code>$b</code> as well as <code>$a</code>. However, this would not be consistent with how we expect the mathematical operators to work.</p>

<p>Perl resolves this dilemma by transparently calling a copy constructor before calling a method defined to implement a mutator (<code>--</code>, <code>+=</code>, and so on.). In the above example, when Perl reaches the decrement statement, it makes a copy of the object data in <code>$a</code> and assigns to <code>$a</code> a reference to the copied data. Only then does it call <code>decr()</code>, which alters the copied data, leaving <code>$b</code> unchanged. Thus the object metaphor is preserved as far as possible, while mathemagical operations still work according to the arithmetic metaphor.</p>

<p>Note: the preceding paragraph describes what happens when Perl autogenerates the copy constructor for an object based on a scalar. For other cases, see <a href="overload.html#Copy-Constructor">&quot;Copy Constructor&quot;</a>.</p>

<h2 id="Overloadable-Operations"><a class="permalink" href="overload.html#Overloadable-Operations">#</a><a id="Overloadable"></a>Overloadable Operations</h2>

<p>The complete list of keys that can be specified in the <code>use overload</code> directive are given, separated by spaces, in the values of the hash <code>%overload::ops</code>:</p>

<pre><code class="plaintext">with_assign	  =&gt; &#39;+ - * / % ** &lt;&lt; &gt;&gt; x .&#39;,
assign		  =&gt; &#39;+= -= *= /= %= **= &lt;&lt;= &gt;&gt;= x= .=&#39;,
num_comparison	  =&gt; &#39;&lt; &lt;= &gt; &gt;= == !=&#39;,
&#39;3way_comparison&#39;=&gt; &#39;&lt;=&gt; cmp&#39;,
str_comparison	  =&gt; &#39;lt le gt ge eq ne&#39;,
binary		  =&gt; &#39;&amp; &amp;= | |= ^ ^= &amp;. &amp;.= |. |.= ^. ^.=&#39;,
unary		  =&gt; &#39;neg ! ~ ~.&#39;,
mutators	  =&gt; &#39;++ --&#39;,
func		  =&gt; &#39;atan2 cos sin exp abs log sqrt int&#39;,
conversion	  =&gt; &#39;bool &quot;&quot; 0+ qr&#39;,
iterators	  =&gt; &#39;&lt;&gt;&#39;,
filetest         =&gt; &#39;-X&#39;,
dereferencing	  =&gt; &#39;${} @{} %{} &amp;{} *{}&#39;,
matching	  =&gt; &#39;~~&#39;,
special	  =&gt; &#39;nomethod fallback =&#39;</code></pre>

<p>Most of the overloadable operators map one-to-one to these keys. Exceptions, including additional overloadable operations not apparent from this hash, are included in the notes which follow. This list is subject to growth over time.</p>

<p>A warning is issued if an attempt is made to register an operator not found above.</p>

<ul>

<li><p><code>not</code></p>

<p>The operator <code>not</code> is not a valid key for <code>use overload</code>. However, if the operator <code>!</code> is overloaded then the same implementation will be used for <code>not</code> (since the two operators differ only in precedence).</p>

</li>
<li><p><code>neg</code></p>

<p>The key <code>neg</code> is used for unary minus to disambiguate it from binary <code>-</code>.</p>

</li>
<li><p><code>++</code>, <code>--</code></p>

<p>Assuming they are to behave analogously to Perl&#39;s <code>++</code> and <code>--</code>, overloaded implementations of these operators are required to mutate their operands.</p>

<p>No distinction is made between prefix and postfix forms of the increment and decrement operators: these differ only in the point at which Perl calls the associated subroutine when evaluating an expression.</p>

</li>
<li><p><i>Assignments</i></p>

<pre><code class="plaintext">+=  -=  *=  /=  %=  **=  &lt;&lt;=  &gt;&gt;=  x=  .=
&amp;=  |=  ^=  &amp;.=  |.=  ^.=</code></pre>

<p>Simple assignment is not overloadable (the <code>&#39;=&#39;</code> key is used for the <a href="overload.html#Copy-Constructor">&quot;Copy Constructor&quot;</a>). Perl does have a way to make assignments to an object do whatever you want, but this involves using tie(), not overload - see <a href="perlfunc.html#tie">&quot;tie&quot; in perlfunc</a> and the <a href="overload.html#COOKBOOK">&quot;COOKBOOK&quot;</a> examples below.</p>

<p>The subroutine for the assignment variant of an operator is required only to return the result of the operation. It is permitted to change the value of its operand (this is safe because Perl calls the copy constructor first), but this is optional since Perl assigns the returned value to the left-hand operand anyway.</p>

<p>An object that overloads an assignment operator does so only in respect of assignments to that object. In other words, Perl never calls the corresponding methods with the third argument (the &quot;swap&quot; argument) set to TRUE. For example, the operation</p>

<pre><code>$a *= $b</code></pre>

<p>cannot lead to <code>$b</code>&#39;s implementation of <code>*=</code> being called, even if <code>$a</code> is a scalar. (It can, however, generate a call to <code>$b</code>&#39;s method for <code>*</code>).</p>

</li>
<li><p><i>Non-mutators with a mutator variant</i></p>

<pre><code class="plaintext">+  -  *  /  %  **  &lt;&lt;  &gt;&gt;  x  .
&amp;  |  ^  &amp;.  |.  ^.</code></pre>

<p>As described <a href="overload.html#Calling-Conventions-and-Magic-Autogeneration">above</a>, Perl may call methods for operators like <code>+</code> and <code>&amp;</code> in the course of implementing missing operations like <code>++</code>, <code>+=</code>, and <code>&amp;=</code>. While these methods may detect this usage by testing the definedness of the third argument, they should in all cases avoid changing their operands. This is because Perl does not call the copy constructor before invoking these methods.</p>

</li>
<li><p><code>int</code></p>

<p>Traditionally, the Perl function <code>int</code> rounds to 0 (see <a href="perlfunc.html#int">&quot;int&quot; in perlfunc</a>), and so for floating-point-like types one should follow the same semantic.</p>

</li>
<li><p><i>String, numeric, boolean, and regexp conversions</i></p>

<pre><code class="plaintext">&quot;&quot;  0+  bool</code></pre>

<p>These conversions are invoked according to context as necessary. For example, the subroutine for <code>&#39;&quot;&quot;&#39;</code> (stringify) may be used where the overloaded object is passed as an argument to <code>print</code>, and that for <code>&#39;bool&#39;</code> where it is tested in the condition of a flow control statement (like <code>while</code>) or the ternary <code>?:</code> operation.</p>

<p>Of course, in contexts like, for example, <code>$obj + 1</code>, Perl will invoke <code>$obj</code>&#39;s implementation of <code>+</code> rather than (in this example) converting <code>$obj</code> to a number using the numify method <code>&#39;0+&#39;</code> (an exception to this is when no method has been provided for <code>&#39;+&#39;</code> and <a href="overload.html#fallback">&quot;fallback&quot;</a> is set to TRUE).</p>

<p>The subroutines for <code>&#39;&quot;&quot;&#39;</code>, <code>&#39;0+&#39;</code>, and <code>&#39;bool&#39;</code> can return any arbitrary Perl value. If the corresponding operation for this value is overloaded too, the operation will be called again with this value.</p>

<p>As a special case if the overload returns the object itself then it will be used directly. An overloaded conversion returning the object is probably a bug, because you&#39;re likely to get something that looks like <code>YourPackage=HASH(0x8172b34)</code>.</p>

<pre><code class="plaintext">qr</code></pre>

<p>The subroutine for <code>&#39;qr&#39;</code> is used wherever the object is interpolated into or used as a regexp, including when it appears on the RHS of a <code>=~</code> or <code>!~</code> operator.</p>

<p><code>qr</code> must return a compiled regexp, or a ref to a compiled regexp (such as <code>qr//</code> returns), and any further overloading on the return value will be ignored.</p>

</li>
<li><p><i>Iteration</i></p>

<p>If <code>&lt;&gt;</code> is overloaded then the same implementation is used for both the <i>read-filehandle</i> syntax <code>&lt;$var&gt;</code> and <i>globbing</i> syntax <code>&lt;${var}&gt;</code>.</p>

</li>
<li><p><i>File tests</i></p>

<p>The key <code>&#39;-X&#39;</code> is used to specify a subroutine to handle all the filetest operators (<code>-f</code>, <code>-x</code>, and so on: see <a href="perlfunc.html#-X">&quot;-X&quot; in perlfunc</a> for the full list); it is not possible to overload any filetest operator individually. To distinguish them, the letter following the &#39;-&#39; is passed as the second argument (that is, in the slot that for binary operators is used to pass the second operand).</p>

<p>Calling an overloaded filetest operator does not affect the stat value associated with the special filehandle <code>_</code>. It still refers to the result of the last <code>stat</code>, <code>lstat</code> or unoverloaded filetest.</p>

<p>This overload was introduced in Perl 5.12.</p>

</li>
<li><p><i>Matching</i></p>

<p>The key <code>&quot;~~&quot;</code> allows you to override the smart matching logic used by the <code>~~</code> operator and the switch construct (<code>given</code>/<code>when</code>). See <a href="perlsyn.html#Switch-Statements">&quot;Switch Statements&quot; in perlsyn</a> and <a href="feature.html">feature</a>.</p>

<p>Unusually, the overloaded implementation of the smart match operator does not get full control of the smart match behaviour. In particular, in the following code:</p>

<pre><code>package Foo;
use overload &#39;~~&#39; =&gt; &#39;match&#39;;

my $obj =  Foo-&gt;new();
$obj ~~ [ 1,2,3 ];</code></pre>

<p>the smart match does <i>not</i> invoke the method call like this:</p>

<pre><code>$obj-&gt;match([1,2,3],0);</code></pre>

<p>rather, the smart match distributive rule takes precedence, so $obj is smart matched against each array element in turn until a match is found, so you may see between one and three of these calls instead:</p>

<pre><code>$obj-&gt;match(1,0);
$obj-&gt;match(2,0);
$obj-&gt;match(3,0);</code></pre>

<p>Consult the match table in <a href="perlop.html#Smartmatch-Operator">&quot;Smartmatch Operator&quot; in perlop</a> for details of when overloading is invoked.</p>

</li>
<li><p><i>Dereferencing</i></p>

<pre><code class="plaintext">${}  @{}  %{}  &amp;{}  *{}</code></pre>

<p>If these operators are not explicitly overloaded then they work in the normal way, yielding the underlying scalar, array, or whatever stores the object data (or the appropriate error message if the dereference operator doesn&#39;t match it). Defining a catch-all <code>&#39;nomethod&#39;</code> (see <a href="overload.html#nomethod">below</a>) makes no difference to this as the catch-all function will not be called to implement a missing dereference operator.</p>

<p>If a dereference operator is overloaded then it must return a <i>reference</i> of the appropriate type (for example, the subroutine for key <code>&#39;${}&#39;</code> should return a reference to a scalar, not a scalar), or another object which overloads the operator: that is, the subroutine only determines what is dereferenced and the actual dereferencing is left to Perl. As a special case, if the subroutine returns the object itself then it will not be called again - avoiding infinite recursion.</p>

</li>
<li><p><i>Special</i></p>

<pre><code class="plaintext">nomethod  fallback  =</code></pre>

<p>See <a href="overload.html#Special-Keys-for-use-overload">&quot;Special Keys for <code>use overload</code>&quot;</a>.</p>

</li>
</ul>

<h2 id="Magic-Autogeneration"><a class="permalink" href="overload.html#Magic-Autogeneration">#</a><a id="Magic"></a>Magic Autogeneration</h2>

<p>If a method for an operation is not found then Perl tries to autogenerate a substitute implementation from the operations that have been defined.</p>

<p>Note: the behaviour described in this section can be disabled by setting <code>fallback</code> to FALSE (see <a href="overload.html#fallback">&quot;fallback&quot;</a>).</p>

<p>In the following tables, numbers indicate priority. For example, the table below states that, if no implementation for <code>&#39;!&#39;</code> has been defined then Perl will implement it using <code>&#39;bool&#39;</code> (that is, by inverting the value returned by the method for <code>&#39;bool&#39;</code>); if boolean conversion is also unimplemented then Perl will use <code>&#39;0+&#39;</code> or, failing that, <code>&#39;&quot;&quot;&#39;</code>.</p>

<pre><code class="plaintext">operator | can be autogenerated from
         |
         | 0+   &quot;&quot;   bool   .   x
=========|==========================
   0+    |       1     2
   &quot;&quot;    |  1          2
   bool  |  1    2
   int   |  1    2     3
   !     |  2    3     1
   qr    |  2    1     3
   .     |  2    1     3
   x     |  2    1     3
   .=    |  3    2     4    1
   x=    |  3    2     4        1
   &lt;&gt;    |  2    1     3
   -X    |  2    1     3</code></pre>

<p>Note: The iterator (<code>&#39;&lt;&gt;&#39;</code>) and file test (<code>&#39;-X&#39;</code>) operators work as normal: if the operand is not a blessed glob or IO reference then it is converted to a string (using the method for <code>&#39;&quot;&quot;&#39;</code>, <code>&#39;0+&#39;</code>, or <code>&#39;bool&#39;</code>) to be interpreted as a glob or filename.</p>

<pre><code class="plaintext">operator | can be autogenerated from
         |
         |  &lt;   &lt;=&gt;   neg   -=    -
=========|==========================
   neg   |                        1
   -=    |                        1
   --    |                   1    2
   abs   | a1    a2    b1        b2    [*]
   &lt;     |        1
   &lt;=    |        1
   &gt;     |        1
   &gt;=    |        1
   ==    |        1
   !=    |        1

* one from [a1, a2] and one from [b1, b2]</code></pre>

<p>Just as numeric comparisons can be autogenerated from the method for <code>&#39;&lt;=&gt;&#39;</code>, string comparisons can be autogenerated from that for <code>&#39;cmp&#39;</code>:</p>

<pre><code class="plaintext"> operators          |  can be autogenerated from
====================|===========================
 lt gt le ge eq ne  |  cmp</code></pre>

<p>Similarly, autogeneration for keys <code>&#39;+=&#39;</code> and <code>&#39;++&#39;</code> is analogous to <code>&#39;-=&#39;</code> and <code>&#39;--&#39;</code> above:</p>

<pre><code class="plaintext">operator | can be autogenerated from
         |
         |  +=    +
=========|==========================
    +=   |        1
    ++   |   1    2</code></pre>

<p>And other assignment variations are analogous to <code>&#39;+=&#39;</code> and <code>&#39;-=&#39;</code> (and similar to <code>&#39;.=&#39;</code> and <code>&#39;x=&#39;</code> above):</p>

<pre><code class="plaintext">          operator ||  *= /= %= **= &lt;&lt;= &gt;&gt;= &amp;= ^= |= &amp;.= ^.= |.=
-------------------||-------------------------------------------
autogenerated from ||  *  /  %  **  &lt;&lt;  &gt;&gt;  &amp;  ^  |  &amp;.  ^.  |.</code></pre>

<p>Note also that the copy constructor (key <code>&#39;=&#39;</code>) may be autogenerated, but only for objects based on scalars. See <a href="overload.html#Copy-Constructor">&quot;Copy Constructor&quot;</a>.</p>

<h3 id="Minimal-Set-of-Overloaded-Operations"><a class="permalink" href="overload.html#Minimal-Set-of-Overloaded-Operations">#</a><a id="Minimal"></a>Minimal Set of Overloaded Operations</h3>

<p>Since some operations can be automatically generated from others, there is a minimal set of operations that need to be overloaded in order to have the complete set of overloaded operations at one&#39;s disposal. Of course, the autogenerated operations may not do exactly what the user expects. The minimal set is:</p>

<pre><code class="plaintext">+ - * / % ** &lt;&lt; &gt;&gt; x
&lt;=&gt; cmp
&amp; | ^ ~ &amp;. |. ^. ~.
atan2 cos sin exp log sqrt int
&quot;&quot; 0+ bool
~~</code></pre>

<p>Of the conversions, only one of string, boolean or numeric is needed because each can be generated from either of the other two.</p>

<h2 id="Special-Keys-for-use-overload"><a class="permalink" href="overload.html#Special-Keys-for-use-overload">#</a><a id="Special"></a>Special Keys for <code>use overload</code></h2>

<h3 id="nomethod"><a class="permalink" href="overload.html#nomethod">#</a><code>nomethod</code></h3>

<p>The <code>&#39;nomethod&#39;</code> key is used to specify a catch-all function to be called for any operator that is not individually overloaded. The specified function will be passed four parameters. The first three arguments coincide with those that would have been passed to the corresponding method if it had been defined. The fourth argument is the <code>use overload</code> key for that missing method. If the &quot;bitwise&quot; feature is enabled (see <a href="feature.html">feature</a>), a fifth TRUE argument is passed to subroutines handling <code>&amp;</code>, <code>|</code>, <code>^</code> and <code>~</code> to indicate that the caller is expecting numeric behaviour.</p>

<p>For example, if <code>$a</code> is an object blessed into a package declaring</p>

<pre><code class="plaintext">use overload &#39;nomethod&#39; =&gt; &#39;catch_all&#39;, # ...</code></pre>

<p>then the operation</p>

<pre><code>3 + $a</code></pre>

<p>could (unless a method is specifically declared for the key <code>&#39;+&#39;</code>) result in a call</p>

<pre><code>catch_all($a, 3, 1, &#39;+&#39;)</code></pre>

<p>See <a href="overload.html#How-Perl-Chooses-an-Operator-Implementation">&quot;How Perl Chooses an Operator Implementation&quot;</a>.</p>

<h3 id="fallback"><a class="permalink" href="overload.html#fallback">#</a><code>fallback</code></h3>

<p>The value assigned to the key <code>&#39;fallback&#39;</code> tells Perl how hard it should try to find an alternative way to implement a missing operator.</p>

<ul>

<li><p>defined, but FALSE</p>

<pre><code>use overload &quot;fallback&quot; =&gt; 0, # ... ;</code></pre>

<p>This disables <a href="overload.html#Magic-Autogeneration">&quot;Magic Autogeneration&quot;</a>.</p>

</li>
<li><p><code>undef</code></p>

<p>In the default case where no value is explicitly assigned to <code>fallback</code>, magic autogeneration is enabled.</p>

</li>
<li><p>TRUE</p>

<p>The same as for <code>undef</code>, but if a missing operator cannot be autogenerated then, instead of issuing an error message, Perl is allowed to revert to what it would have done for that operator if there had been no <code>use overload</code> directive.</p>

<p>Note: in most cases, particularly the <a href="overload.html#Copy-Constructor">&quot;Copy Constructor&quot;</a>, this is unlikely to be appropriate behaviour.</p>

</li>
</ul>

<p>See <a href="overload.html#How-Perl-Chooses-an-Operator-Implementation">&quot;How Perl Chooses an Operator Implementation&quot;</a>.</p>

<h3 id="Copy-Constructor"><a class="permalink" href="overload.html#Copy-Constructor">#</a><a id="Copy"></a>Copy Constructor</h3>

<p>As mentioned <a href="overload.html#Mathemagic%2C-Mutators%2C-and-Copy-Constructors">above</a>, this operation is called when a mutator is applied to a reference that shares its object with some other reference. For example, if <code>$b</code> is mathemagical, and <code>&#39;++&#39;</code> is overloaded with <code>&#39;incr&#39;</code>, and <code>&#39;=&#39;</code> is overloaded with <code>&#39;clone&#39;</code>, then the code</p>

<pre><code>$a = $b;
# ... (other code which does not modify $a or $b) ...
++$b;</code></pre>

<p>would be executed in a manner equivalent to</p>

<pre><code>$a = $b;
# ...
$b = $b-&gt;clone(undef, &quot;&quot;);
$b-&gt;incr(undef, &quot;&quot;);</code></pre>

<p>Note:</p>

<ul>

<li><p>The subroutine for <code>&#39;=&#39;</code> does not overload the Perl assignment operator: it is used only to allow mutators to work as described here. (See <a href="overload.html#Assignments">&quot;Assignments&quot;</a> above.)</p>

</li>
<li><p>As for other operations, the subroutine implementing &#39;=&#39; is passed three arguments, though the last two are always <code>undef</code> and <code>&#39;&#39;</code>.</p>

</li>
<li><p>The copy constructor is called only before a call to a function declared to implement a mutator, for example, if <code>++$b;</code> in the code above is effected via a method declared for key <code>&#39;++&#39;</code> (or &#39;nomethod&#39;, passed <code>&#39;++&#39;</code> as the fourth argument) or, by autogeneration, <code>&#39;+=&#39;</code>. It is not called if the increment operation is effected by a call to the method for <code>&#39;+&#39;</code> since, in the equivalent code,</p>

<pre><code>$a = $b;
$b = $b + 1;</code></pre>

<p>the data referred to by <code>$a</code> is unchanged by the assignment to <code>$b</code> of a reference to new object data.</p>

</li>
<li><p>The copy constructor is not called if Perl determines that it is unnecessary because there is no other reference to the data being modified.</p>

</li>
<li><p>If <code>&#39;fallback&#39;</code> is undefined or TRUE then a copy constructor can be autogenerated, but only for objects based on scalars. In other cases it needs to be defined explicitly. Where an object&#39;s data is stored as, for example, an array of scalars, the following might be appropriate:</p>

<pre><code>use overload &#39;=&#39; =&gt; sub { bless [ @{$_[0]} ] },  # ...</code></pre>

</li>
<li><p>If <code>&#39;fallback&#39;</code> is TRUE and no copy constructor is defined then, for objects not based on scalars, Perl may silently fall back on simple assignment - that is, assignment of the object reference. In effect, this disables the copy constructor mechanism since no new copy of the object data is created. This is almost certainly not what you want. (It is, however, consistent: for example, Perl&#39;s fallback for the <code>++</code> operator is to increment the reference itself.)</p>

</li>
</ul>

<h2 id="How-Perl-Chooses-an-Operator-Implementation"><a class="permalink" href="overload.html#How-Perl-Chooses-an-Operator-Implementation">#</a><a id="How"></a>How Perl Chooses an Operator Implementation</h2>

<p>Which is checked first, <code>nomethod</code> or <code>fallback</code>? If the two operands of an operator are of different types and both overload the operator, which implementation is used? The following are the precedence rules:</p>

<ol>

<li><p>If the first operand has declared a subroutine to overload the operator then use that implementation.</p>

</li>
<li><p>Otherwise, if fallback is TRUE or undefined for the first operand then see if the <a href="overload.html#Magic-Autogeneration">rules for autogeneration</a> allows another of its operators to be used instead.</p>

</li>
<li><p>Unless the operator is an assignment (<code>+=</code>, <code>-=</code>, etc.), repeat step (1) in respect of the second operand.</p>

</li>
<li><p>Repeat Step (2) in respect of the second operand.</p>

</li>
<li><p>If the first operand has a &quot;nomethod&quot; method then use that.</p>

</li>
<li><p>If the second operand has a &quot;nomethod&quot; method then use that.</p>

</li>
<li><p>If <code>fallback</code> is TRUE for both operands then perform the usual operation for the operator, treating the operands as numbers, strings, or booleans as appropriate for the operator (see note).</p>

</li>
<li><p>Nothing worked - die.</p>

</li>
</ol>

<p>Where there is only one operand (or only one operand with overloading) the checks in respect of the other operand above are skipped.</p>

<p>There are exceptions to the above rules for dereference operations (which, if Step 1 fails, always fall back to the normal, built-in implementations - see Dereferencing), and for <code>~~</code> (which has its own set of rules - see <code>Matching</code> under <a href="overload.html#Overloadable-Operations">&quot;Overloadable Operations&quot;</a> above).</p>

<p>Note on Step 7: some operators have a different semantic depending on the type of their operands. As there is no way to instruct Perl to treat the operands as, e.g., numbers instead of strings, the result here may not be what you expect. See <a href="overload.html#BUGS-AND-PITFALLS">&quot;BUGS AND PITFALLS&quot;</a>.</p>

<h2 id="Losing-Overloading"><a class="permalink" href="overload.html#Losing-Overloading">#</a><a id="Losing"></a>Losing Overloading</h2>

<p>The restriction for the comparison operation is that even if, for example, <code>cmp</code> should return a blessed reference, the autogenerated <code>lt</code> function will produce only a standard logical value based on the numerical value of the result of <code>cmp</code>. In particular, a working numeric conversion is needed in this case (possibly expressed in terms of other conversions).</p>

<p>Similarly, <code>.=</code> and <code>x=</code> operators lose their mathemagical properties if the string conversion substitution is applied.</p>

<p>When you chop() a mathemagical object it is promoted to a string and its mathemagical properties are lost. The same can happen with other operations as well.</p>

<h2 id="Inheritance-and-Overloading"><a class="permalink" href="overload.html#Inheritance-and-Overloading">#</a><a id="Inheritance"></a>Inheritance and Overloading</h2>

<p>Overloading respects inheritance via the @ISA hierarchy. Inheritance interacts with overloading in two ways.</p>

<dl>

<dt id="Method-names-in-the-use-overload-directive"><a class="permalink" href="overload.html#Method-names-in-the-use-overload-directive">#</a><a id="Method"></a>Method names in the <code>use overload</code> directive</dt>
<dd>

<p>If <code>value</code> in</p>

<pre><code>use overload key =&gt; value;</code></pre>

<p>is a string, it is interpreted as a method name - which may (in the usual way) be inherited from another class.</p>

</dd>
<dt id="Overloading-of-an-operation-is-inherited-by-derived-classes"><a class="permalink" href="overload.html#Overloading-of-an-operation-is-inherited-by-derived-classes">#</a><a id="Overloading"></a>Overloading of an operation is inherited by derived classes</dt>
<dd>

<p>Any class derived from an overloaded class is also overloaded and inherits its operator implementations. If the same operator is overloaded in more than one ancestor then the implementation is determined by the usual inheritance rules.</p>

<p>For example, if <code>A</code> inherits from <code>B</code> and <code>C</code> (in that order), <code>B</code> overloads <code>+</code> with <code>\&amp;D::plus_sub</code>, and <code>C</code> overloads <code>+</code> by <code>&quot;plus_meth&quot;</code>, then the subroutine <code>D::plus_sub</code> will be called to implement operation <code>+</code> for an object in package <code>A</code>.</p>

</dd>
</dl>

<p>Note that in Perl version prior to 5.18 inheritance of the <code>fallback</code> key was not governed by the above rules. The value of <code>fallback</code> in the first overloaded ancestor was used. This was fixed in 5.18 to follow the usual rules of inheritance.</p>

<h2 id="Run-time-Overloading"><a class="permalink" href="overload.html#Run-time-Overloading">#</a><a id="Run"></a>Run-time Overloading</h2>

<p>Since all <code>use</code> directives are executed at compile-time, the only way to change overloading during run-time is to</p>

<pre><code>eval &#39;use overload &quot;+&quot; =&gt; \&amp;addmethod&#39;;</code></pre>

<p>You can also use</p>

<pre><code>eval &#39;no overload &quot;+&quot;, &quot;--&quot;, &quot;&lt;=&quot;&#39;;</code></pre>

<p>though the use of these constructs during run-time is questionable.</p>

<h2 id="Public-Functions"><a class="permalink" href="overload.html#Public-Functions">#</a><a id="Public"></a>Public Functions</h2>

<p>Package <code>overload.pm</code> provides the following public functions:</p>

<dl>

<dt id="overload::StrVal(arg)"><a class="permalink" href="overload.html#overload::StrVal(arg)">#</a><a id="overload"></a><a id="overload::StrVal-arg"></a>overload::StrVal(arg)</dt>
<dd>

<p>Gives the string value of <code>arg</code> as in the absence of stringify overloading. If you are using this to get the address of a reference (useful for checking if two references point to the same thing) then you may be better off using <code>Scalar::Util::refaddr()</code>, which is faster.</p>

</dd>
<dt id="overload::Overloaded(arg)"><a class="permalink" href="overload.html#overload::Overloaded(arg)">#</a><a id="overload1"></a><a id="overload::Overloaded-arg"></a>overload::Overloaded(arg)</dt>
<dd>

<p>Returns true if <code>arg</code> is subject to overloading of some operations.</p>

</dd>
<dt id="overload::Method(obj,op)"><a class="permalink" href="overload.html#overload::Method(obj,op)">#</a><a id="overload2"></a><a id="overload::Method-obj-op"></a>overload::Method(obj,op)</dt>
<dd>

<p>Returns <code>undef</code> or a reference to the method that implements <code>op</code>.</p>

</dd>
</dl>

<h2 id="Overloading-Constants"><a class="permalink" href="overload.html#Overloading-Constants">#</a><a id="Overloading1"></a>Overloading Constants</h2>

<p>For some applications, the Perl parser mangles constants too much. It is possible to hook into this process via <code>overload::constant()</code> and <code>overload::remove_constant()</code> functions.</p>

<p>These functions take a hash as an argument. The recognized keys of this hash are:</p>

<dl>

<dt id="integer"><a class="permalink" href="overload.html#integer">#</a>integer</dt>
<dd>

<p>to overload integer constants,</p>

</dd>
<dt id="float"><a class="permalink" href="overload.html#float">#</a>float</dt>
<dd>

<p>to overload floating point constants,</p>

</dd>
<dt id="binary"><a class="permalink" href="overload.html#binary">#</a>binary</dt>
<dd>

<p>to overload octal and hexadecimal constants,</p>

</dd>
<dt id="q"><a class="permalink" href="overload.html#q">#</a>q</dt>
<dd>

<p>to overload <code>q</code>-quoted strings, constant pieces of <code>qq</code>- and <code>qx</code>-quoted strings and here-documents,</p>

</dd>
<dt id="qr"><a class="permalink" href="overload.html#qr">#</a>qr</dt>
<dd>

<p>to overload constant pieces of regular expressions.</p>

</dd>
</dl>

<p>The corresponding values are references to functions which take three arguments: the first one is the <i>initial</i> string form of the constant, the second one is how Perl interprets this constant, the third one is how the constant is used. Note that the initial string form does not contain string delimiters, and has backslashes in backslash-delimiter combinations stripped (thus the value of delimiter is not relevant for processing of this string). The return value of this function is how this constant is going to be interpreted by Perl. The third argument is undefined unless for overloaded <code>q</code>- and <code>qr</code>- constants, it is <code>q</code> in single-quote context (comes from strings, regular expressions, and single-quote HERE documents), it is <code>tr</code> for arguments of <code>tr</code>/<code>y</code> operators, it is <code>s</code> for right-hand side of <code>s</code>-operator, and it is <code>qq</code> otherwise.</p>

<p>Since an expression <code>&quot;ab$cd,,&quot;</code> is just a shortcut for <code>&#39;ab&#39; . $cd . &#39;,,&#39;</code>, it is expected that overloaded constant strings are equipped with reasonable overloaded catenation operator, otherwise absurd results will result. Similarly, negative numbers are considered as negations of positive constants.</p>

<p>Note that it is probably meaningless to call the functions overload::constant() and overload::remove_constant() from anywhere but import() and unimport() methods. From these methods they may be called as</p>

<pre><code>sub import {
   shift;
   return unless @_;
   die &quot;unknown import: @_&quot; unless @_ == 1 and $_[0] eq &#39;:constant&#39;;
   overload::constant integer =&gt; sub {Math::BigInt-&gt;new(shift)};
}</code></pre>

<h1 id="IMPLEMENTATION"><a class="permalink" href="overload.html#IMPLEMENTATION">#</a>IMPLEMENTATION</h1>

<p>What follows is subject to change RSN.</p>

<p>The table of methods for all operations is cached in magic for the symbol table hash for the package. The cache is invalidated during processing of <code>use overload</code>, <code>no overload</code>, new function definitions, and changes in @ISA.</p>

<p>(Every SVish thing has a magic queue, and magic is an entry in that queue. This is how a single variable may participate in multiple forms of magic simultaneously. For instance, environment variables regularly have two forms at once: their %ENV magic and their taint magic. However, the magic which implements overloading is applied to the stashes, which are rarely used directly, thus should not slow down Perl.)</p>

<p>If a package uses overload, it carries a special flag. This flag is also set when new functions are defined or @ISA is modified. There will be a slight speed penalty on the very first operation thereafter that supports overloading, while the overload tables are updated. If there is no overloading present, the flag is turned off. Thus the only speed penalty thereafter is the checking of this flag.</p>

<p>It is expected that arguments to methods that are not explicitly supposed to be changed are constant (but this is not enforced).</p>

<h1 id="COOKBOOK"><a class="permalink" href="overload.html#COOKBOOK">#</a>COOKBOOK</h1>

<p>Please add examples to what follows!</p>

<h2 id="Two-face-Scalars"><a class="permalink" href="overload.html#Two-face-Scalars">#</a><a id="Two"></a>Two-face Scalars</h2>

<p>Put this in <i>two_face.pm</i> in your Perl library directory:</p>

<pre><code>package two_face;		# Scalars with separate string and
                              # numeric values.
sub new { my $p = shift; bless [@_], $p }
use overload &#39;&quot;&quot;&#39; =&gt; \&amp;str, &#39;0+&#39; =&gt; \&amp;num, fallback =&gt; 1;
sub num {shift-&gt;[1]}
sub str {shift-&gt;[0]}</code></pre>

<p>Use it as follows:</p>

<pre><code>require two_face;
my $seven = two_face-&gt;new(&quot;vii&quot;, 7);
printf &quot;seven=$seven, seven=%d, eight=%d\n&quot;, $seven, $seven+1;
print &quot;seven contains &#39;i&#39;\n&quot; if $seven =~ /i/;</code></pre>

<p>(The second line creates a scalar which has both a string value, and a numeric value.) This prints:</p>

<pre><code class="plaintext">seven=vii, seven=7, eight=8
seven contains &#39;i&#39;</code></pre>

<h2 id="Two-face-References"><a class="permalink" href="overload.html#Two-face-References">#</a><a id="Two1"></a>Two-face References</h2>

<p>Suppose you want to create an object which is accessible as both an array reference and a hash reference.</p>

<pre><code>package two_refs;
use overload &#39;%{}&#39; =&gt; \&amp;gethash, &#39;@{}&#39; =&gt; sub { $ {shift()} };
sub new {
  my $p = shift;
  bless \ [@_], $p;
}
sub gethash {
  my %h;
  my $self = shift;
  tie %h, ref $self, $self;
  \%h;
}

sub TIEHASH { my $p = shift; bless \ shift, $p }
my %fields;
my $i = 0;
$fields{$_} = $i++ foreach qw{zero one two three};
sub STORE {
  my $self = ${shift()};
  my $key = $fields{shift()};
  defined $key or die &quot;Out of band access&quot;;
  $$self-&gt;[$key] = shift;
}
sub FETCH {
  my $self = ${shift()};
  my $key = $fields{shift()};
  defined $key or die &quot;Out of band access&quot;;
  $$self-&gt;[$key];
}</code></pre>

<p>Now one can access an object using both the array and hash syntax:</p>

<pre><code>my $bar = two_refs-&gt;new(3,4,5,6);
$bar-&gt;[2] = 11;
$bar-&gt;{two} == 11 or die &#39;bad hash fetch&#39;;</code></pre>

<p>Note several important features of this example. First of all, the <i>actual</i> type of $bar is a scalar reference, and we do not overload the scalar dereference. Thus we can get the <i>actual</i> non-overloaded contents of $bar by just using <code>$$bar</code> (what we do in functions which overload dereference). Similarly, the object returned by the TIEHASH() method is a scalar reference.</p>

<p>Second, we create a new tied hash each time the hash syntax is used. This allows us not to worry about a possibility of a reference loop, which would lead to a memory leak.</p>

<p>Both these problems can be cured. Say, if we want to overload hash dereference on a reference to an object which is <i>implemented</i> as a hash itself, the only problem one has to circumvent is how to access this <i>actual</i> hash (as opposed to the <i>virtual</i> hash exhibited by the overloaded dereference operator). Here is one possible fetching routine:</p>

<pre><code>sub access_hash {
  my ($self, $key) = (shift, shift);
  my $class = ref $self;
  bless $self, &#39;overload::dummy&#39;; # Disable overloading of %{}
  my $out = $self-&gt;{$key};
  bless $self, $class;	# Restore overloading
  $out;
}</code></pre>

<p>To remove creation of the tied hash on each access, one may an extra level of indirection which allows a non-circular structure of references:</p>

<pre><code>package two_refs1;
use overload &#39;%{}&#39; =&gt; sub { ${shift()}-&gt;[1] },
             &#39;@{}&#39; =&gt; sub { ${shift()}-&gt;[0] };
sub new {
  my $p = shift;
  my $a = [@_];
  my %h;
  tie %h, $p, $a;
  bless \ [$a, \%h], $p;
}
sub gethash {
  my %h;
  my $self = shift;
  tie %h, ref $self, $self;
  \%h;
}

sub TIEHASH { my $p = shift; bless \ shift, $p }
my %fields;
my $i = 0;
$fields{$_} = $i++ foreach qw{zero one two three};
sub STORE {
  my $a = ${shift()};
  my $key = $fields{shift()};
  defined $key or die &quot;Out of band access&quot;;
  $a-&gt;[$key] = shift;
}
sub FETCH {
  my $a = ${shift()};
  my $key = $fields{shift()};
  defined $key or die &quot;Out of band access&quot;;
  $a-&gt;[$key];
}</code></pre>

<p>Now if $baz is overloaded like this, then <code>$baz</code> is a reference to a reference to the intermediate array, which keeps a reference to an actual array, and the access hash. The tie()ing object for the access hash is a reference to a reference to the actual array, so</p>

<ul>

<li><p>There are no loops of references.</p>

</li>
<li><p>Both &quot;objects&quot; which are blessed into the class <code>two_refs1</code> are references to a reference to an array, thus references to a <i>scalar</i>. Thus the accessor expression <code>$$foo-&gt;[$ind]</code> involves no overloaded operations.</p>

</li>
</ul>

<h2 id="Symbolic-Calculator"><a class="permalink" href="overload.html#Symbolic-Calculator">#</a><a id="Symbolic"></a>Symbolic Calculator</h2>

<p>Put this in <i>symbolic.pm</i> in your Perl library directory:</p>

<pre><code>package symbolic;		# Primitive symbolic calculator
use overload nomethod =&gt; \&amp;wrap;

sub new { shift; bless [&#39;n&#39;, @_] }
sub wrap {
  my ($obj, $other, $inv, $meth) = @_;
  ($obj, $other) = ($other, $obj) if $inv;
  bless [$meth, $obj, $other];
}</code></pre>

<p>This module is very unusual as overloaded modules go: it does not provide any usual overloaded operators, instead it provides an implementation for <code><a href="overload.html#nomethod">&quot;nomethod&quot;</a></code>. In this example the <code>nomethod</code> subroutine returns an object which encapsulates operations done over the objects: <code>symbolic-&gt;new(3)</code> contains <code>[&#39;n&#39;, 3]</code>, <code>2 + symbolic-&gt;new(3)</code> contains <code>[&#39;+&#39;, 2, [&#39;n&#39;, 3]]</code>.</p>

<p>Here is an example of the script which &quot;calculates&quot; the side of circumscribed octagon using the above package:</p>

<pre><code>require symbolic;
my $iter = 1;			# 2**($iter+2) = 8
my $side = symbolic-&gt;new(1);
my $cnt = $iter;

while ($cnt--) {
  $side = (sqrt(1 + $side**2) - 1)/$side;
}
print &quot;OK\n&quot;;</code></pre>

<p>The value of $side is</p>

<pre><code class="plaintext">  [&#39;/&#39;, [&#39;-&#39;, [&#39;sqrt&#39;, [&#39;+&#39;, 1, [&#39;**&#39;, [&#39;n&#39;, 1], 2]],
	               undef], 1], [&#39;n&#39;, 1]]</code></pre>

<p>Note that while we obtained this value using a nice little script, there is no simple way to <i>use</i> this value. In fact this value may be inspected in debugger (see <a href="perldebug.html">perldebug</a>), but only if <code>bareStringify</code> <b>O</b>ption is set, and not via <code>p</code> command.</p>

<p>If one attempts to print this value, then the overloaded operator <code>&quot;&quot;</code> will be called, which will call <code>nomethod</code> operator. The result of this operator will be stringified again, but this result is again of type <code>symbolic</code>, which will lead to an infinite loop.</p>

<p>Add a pretty-printer method to the module <i>symbolic.pm</i>:</p>

<pre><code>sub pretty {
  my ($meth, $a, $b) = @{+shift};
  $a = &#39;u&#39; unless defined $a;
  $b = &#39;u&#39; unless defined $b;
  $a = $a-&gt;pretty if ref $a;
  $b = $b-&gt;pretty if ref $b;
  &quot;[$meth $a $b]&quot;;
}</code></pre>

<p>Now one can finish the script by</p>

<pre><code>print &quot;side = &quot;, $side-&gt;pretty, &quot;\n&quot;;</code></pre>

<p>The method <code>pretty</code> is doing object-to-string conversion, so it is natural to overload the operator <code>&quot;&quot;</code> using this method. However, inside such a method it is not necessary to pretty-print the <i>components</i> $a and $b of an object. In the above subroutine <code>&quot;[$meth $a $b]&quot;</code> is a catenation of some strings and components $a and $b. If these components use overloading, the catenation operator will look for an overloaded operator <code>.</code>; if not present, it will look for an overloaded operator <code>&quot;&quot;</code>. Thus it is enough to use</p>

<pre><code>use overload nomethod =&gt; \&amp;wrap, &#39;&quot;&quot;&#39; =&gt; \&amp;str;
sub str {
  my ($meth, $a, $b) = @{+shift};
  $a = &#39;u&#39; unless defined $a;
  $b = &#39;u&#39; unless defined $b;
  &quot;[$meth $a $b]&quot;;
}</code></pre>

<p>Now one can change the last line of the script to</p>

<pre><code>print &quot;side = $side\n&quot;;</code></pre>

<p>which outputs</p>

<pre><code class="plaintext">side = [/ [- [sqrt [+ 1 [** [n 1 u] 2]] u] 1] [n 1 u]]</code></pre>

<p>and one can inspect the value in debugger using all the possible methods.</p>

<p>Something is still amiss: consider the loop variable $cnt of the script. It was a number, not an object. We cannot make this value of type <code>symbolic</code>, since then the loop will not terminate.</p>

<p>Indeed, to terminate the cycle, the $cnt should become false. However, the operator <code>bool</code> for checking falsity is overloaded (this time via overloaded <code>&quot;&quot;</code>), and returns a long string, thus any object of type <code>symbolic</code> is true. To overcome this, we need a way to compare an object to 0. In fact, it is easier to write a numeric conversion routine.</p>

<p>Here is the text of <i>symbolic.pm</i> with such a routine added (and slightly modified str()):</p>

<pre><code>  package symbolic;		# Primitive symbolic calculator
  use overload
    nomethod =&gt; \&amp;wrap, &#39;&quot;&quot;&#39; =&gt; \&amp;str, &#39;0+&#39; =&gt; \&amp;num;

  sub new { shift; bless [&#39;n&#39;, @_] }
  sub wrap {
    my ($obj, $other, $inv, $meth) = @_;
    ($obj, $other) = ($other, $obj) if $inv;
    bless [$meth, $obj, $other];
  }
  sub str {
    my ($meth, $a, $b) = @{+shift};
    $a = &#39;u&#39; unless defined $a;
    if (defined $b) {
      &quot;[$meth $a $b]&quot;;
    } else {
      &quot;[$meth $a]&quot;;
    }
  }
  my %subr = ( n =&gt; sub {$_[0]},
	       sqrt =&gt; sub {sqrt $_[0]},
	       &#39;-&#39; =&gt; sub {shift() - shift()},
	       &#39;+&#39; =&gt; sub {shift() + shift()},
	       &#39;/&#39; =&gt; sub {shift() / shift()},
	       &#39;*&#39; =&gt; sub {shift() * shift()},
	       &#39;**&#39; =&gt; sub {shift() ** shift()},
	     );
  sub num {
    my ($meth, $a, $b) = @{+shift};
    my $subr = $subr{$meth}
      or die &quot;Do not know how to ($meth) in symbolic&quot;;
    $a = $a-&gt;num if ref $a eq __PACKAGE__;
    $b = $b-&gt;num if ref $b eq __PACKAGE__;
    $subr-&gt;($a,$b);
  }</code></pre>

<p>All the work of numeric conversion is done in %subr and num(). Of course, %subr is not complete, it contains only operators used in the example below. Here is the extra-credit question: why do we need an explicit recursion in num()? (Answer is at the end of this section.)</p>

<p>Use this module like this:</p>

<pre><code>require symbolic;
my $iter = symbolic-&gt;new(2);	# 16-gon
my $side = symbolic-&gt;new(1);
my $cnt = $iter;

while ($cnt) {
  $cnt = $cnt - 1;		# Mutator &#39;--&#39; not implemented
  $side = (sqrt(1 + $side**2) - 1)/$side;
}
printf &quot;%s=%f\n&quot;, $side, $side;
printf &quot;pi=%f\n&quot;, $side*(2**($iter+2));</code></pre>

<p>It prints (without so many line breaks)</p>

<pre><code class="plaintext">  [/ [- [sqrt [+ 1 [** [/ [- [sqrt [+ 1 [** [n 1] 2]]] 1]
			  [n 1]] 2]]] 1]
     [/ [- [sqrt [+ 1 [** [n 1] 2]]] 1] [n 1]]]=0.198912
  pi=3.182598</code></pre>

<p>The above module is very primitive. It does not implement mutator methods (<code>++</code>, <code>-=</code> and so on), does not do deep copying (not required without mutators!), and implements only those arithmetic operations which are used in the example.</p>

<p>To implement most arithmetic operations is easy; one should just use the tables of operations, and change the code which fills %subr to</p>

<pre><code>my %subr = ( &#39;n&#39; =&gt; sub {$_[0]} );
foreach my $op (split &quot; &quot;, $overload::ops{with_assign}) {
  $subr{$op} = $subr{&quot;$op=&quot;} = eval &quot;sub {shift() $op shift()}&quot;;
}
my @bins = qw(binary 3way_comparison num_comparison str_comparison);
foreach my $op (split &quot; &quot;, &quot;@overload::ops{ @bins }&quot;) {
  $subr{$op} = eval &quot;sub {shift() $op shift()}&quot;;
}
foreach my $op (split &quot; &quot;, &quot;@overload::ops{qw(unary func)}&quot;) {
  print &quot;defining &#39;$op&#39;\n&quot;;
  $subr{$op} = eval &quot;sub {$op shift()}&quot;;
}</code></pre>

<p>Since subroutines implementing assignment operators are not required to modify their operands (see <a href="overload.html#Overloadable-Operations">&quot;Overloadable Operations&quot;</a> above), we do not need anything special to make <code>+=</code> and friends work, besides adding these operators to %subr and defining a copy constructor (needed since Perl has no way to know that the implementation of <code>&#39;+=&#39;</code> does not mutate the argument - see <a href="overload.html#Copy-Constructor">&quot;Copy Constructor&quot;</a>).</p>

<p>To implement a copy constructor, add <code>&#39;=&#39; =&gt; \&amp;cpy</code> to <code>use overload</code> line, and code (this code assumes that mutators change things one level deep only, so recursive copying is not needed):</p>

<pre><code>sub cpy {
  my $self = shift;
  bless [@$self], ref $self;
}</code></pre>

<p>To make <code>++</code> and <code>--</code> work, we need to implement actual mutators, either directly, or in <code>nomethod</code>. We continue to do things inside <code>nomethod</code>, thus add</p>

<pre><code>if ($meth eq &#39;++&#39; or $meth eq &#39;--&#39;) {
  @$obj = ($meth, (bless [@$obj]), 1); # Avoid circular reference
  return $obj;
}</code></pre>

<p>after the first line of wrap(). This is not a most effective implementation, one may consider</p>

<pre><code>sub inc { $_[0] = bless [&#39;++&#39;, shift, 1]; }</code></pre>

<p>instead.</p>

<p>As a final remark, note that one can fill %subr by</p>

<pre><code>my %subr = ( &#39;n&#39; =&gt; sub {$_[0]} );
foreach my $op (split &quot; &quot;, $overload::ops{with_assign}) {
  $subr{$op} = $subr{&quot;$op=&quot;} = eval &quot;sub {shift() $op shift()}&quot;;
}
my @bins = qw(binary 3way_comparison num_comparison str_comparison);
foreach my $op (split &quot; &quot;, &quot;@overload::ops{ @bins }&quot;) {
  $subr{$op} = eval &quot;sub {shift() $op shift()}&quot;;
}
foreach my $op (split &quot; &quot;, &quot;@overload::ops{qw(unary func)}&quot;) {
  $subr{$op} = eval &quot;sub {$op shift()}&quot;;
}
$subr{&#39;++&#39;} = $subr{&#39;+&#39;};
$subr{&#39;--&#39;} = $subr{&#39;-&#39;};</code></pre>

<p>This finishes implementation of a primitive symbolic calculator in 50 lines of Perl code. Since the numeric values of subexpressions are not cached, the calculator is very slow.</p>

<p>Here is the answer for the exercise: In the case of str(), we need no explicit recursion since the overloaded <code>.</code>-operator will fall back to an existing overloaded operator <code>&quot;&quot;</code>. Overloaded arithmetic operators <i>do not</i> fall back to numeric conversion if <code>fallback</code> is not explicitly requested. Thus without an explicit recursion num() would convert <code>[&#39;+&#39;, $a, $b]</code> to <code>$a + $b</code>, which would just rebuild the argument of num().</p>

<p>If you wonder why defaults for conversion are different for str() and num(), note how easy it was to write the symbolic calculator. This simplicity is due to an appropriate choice of defaults. One extra note: due to the explicit recursion num() is more fragile than sym(): we need to explicitly check for the type of $a and $b. If components $a and $b happen to be of some related type, this may lead to problems.</p>

<h2 id="Really-Symbolic-Calculator"><a class="permalink" href="overload.html#Really-Symbolic-Calculator">#</a><a id="Really"></a><i>Really</i> Symbolic Calculator</h2>

<p>One may wonder why we call the above calculator symbolic. The reason is that the actual calculation of the value of expression is postponed until the value is <i>used</i>.</p>

<p>To see it in action, add a method</p>

<pre><code>sub STORE {
  my $obj = shift;
  $#$obj = 1;
  @$obj-&gt;[0,1] = (&#39;=&#39;, shift);
}</code></pre>

<p>to the package <code>symbolic</code>. After this change one can do</p>

<pre><code>my $a = symbolic-&gt;new(3);
my $b = symbolic-&gt;new(4);
my $c = sqrt($a**2 + $b**2);</code></pre>

<p>and the numeric value of $c becomes 5. However, after calling</p>

<pre><code>$a-&gt;STORE(12);  $b-&gt;STORE(5);</code></pre>

<p>the numeric value of $c becomes 13. There is no doubt now that the module symbolic provides a <i>symbolic</i> calculator indeed.</p>

<p>To hide the rough edges under the hood, provide a tie()d interface to the package <code>symbolic</code>. Add methods</p>

<pre><code>sub TIESCALAR { my $pack = shift; $pack-&gt;new(@_) }
sub FETCH { shift }
sub nop {  }		# Around a bug</code></pre>

<p>(the bug, fixed in Perl 5.14, is described in <a href="overload.html#BUGS">&quot;BUGS&quot;</a>). One can use this new interface as</p>

<pre><code>tie $a, &#39;symbolic&#39;, 3;
tie $b, &#39;symbolic&#39;, 4;
$a-&gt;nop;  $b-&gt;nop;	# Around a bug

my $c = sqrt($a**2 + $b**2);</code></pre>

<p>Now numeric value of $c is 5. After <code>$a = 12; $b = 5</code> the numeric value of $c becomes 13. To insulate the user of the module add a method</p>

<pre><code>sub vars { my $p = shift; tie($_, $p), $_-&gt;nop foreach @_; }</code></pre>

<p>Now</p>

<pre><code>my ($a, $b);
symbolic-&gt;vars($a, $b);
my $c = sqrt($a**2 + $b**2);

$a = 3; $b = 4;
printf &quot;c5  %s=%f\n&quot;, $c, $c;

$a = 12; $b = 5;
printf &quot;c13  %s=%f\n&quot;, $c, $c;</code></pre>

<p>shows that the numeric value of $c follows changes to the values of $a and $b.</p>

<h1 id="AUTHOR"><a class="permalink" href="overload.html#AUTHOR">#</a>AUTHOR</h1>

<p>Ilya Zakharevich &lt;<i>ilya@math.mps.ohio-state.edu</i>&gt;.</p>

<h1 id="SEE-ALSO"><a class="permalink" href="overload.html#SEE-ALSO">#</a><a id="SEE"></a>SEE ALSO</h1>

<p>The <code>overloading</code> pragma can be used to enable or disable overloaded operations within a lexical scope - see <a href="overloading.html">overloading</a>.</p>

<h1 id="DIAGNOSTICS"><a class="permalink" href="overload.html#DIAGNOSTICS">#</a>DIAGNOSTICS</h1>

<p>When Perl is run with the <b>-Do</b> switch or its equivalent, overloading induces diagnostic messages.</p>

<p>Using the <code>m</code> command of Perl debugger (see <a href="perldebug.html">perldebug</a>) one can deduce which operations are overloaded (and which ancestor triggers this overloading). Say, if <code>eq</code> is overloaded, then the method <code>(eq</code> is shown by debugger. The method <code>()</code> corresponds to the <code>fallback</code> key (in fact a presence of this method shows that this package has overloading enabled, and it is what is used by the <code>Overloaded</code> function of module <code>overload</code>).</p>

<p>The module might issue the following warnings:</p>

<dl>

<dt id="Odd-number-of-arguments-for-overload::constant"><a class="permalink" href="overload.html#Odd-number-of-arguments-for-overload::constant">#</a><a id="Odd"></a>Odd number of arguments for overload::constant</dt>
<dd>

<p>(W) The call to overload::constant contained an odd number of arguments. The arguments should come in pairs.</p>

</dd>
<dt id="&#39;%s&#39;-is-not-an-overloadable-type"><a class="permalink" href="overload.html#&#39;%25s&#39;-is-not-an-overloadable-type">#</a><a id="s-is-not-an-overloadable-type"></a>&#39;%s&#39; is not an overloadable type</dt>
<dd>

<p>(W) You tried to overload a constant type the overload package is unaware of.</p>

</dd>
<dt id="&#39;%s&#39;-is-not-a-code-reference"><a class="permalink" href="overload.html#&#39;%25s&#39;-is-not-a-code-reference">#</a><a id="s-is-not-a-code-reference"></a>&#39;%s&#39; is not a code reference</dt>
<dd>

<p>(W) The second (fourth, sixth, ...) argument of overload::constant needs to be a code reference. Either an anonymous subroutine, or a reference to a subroutine.</p>

</dd>
<dt id="overload-arg-&#39;%s&#39;-is-invalid"><a class="permalink" href="overload.html#overload-arg-&#39;%25s&#39;-is-invalid">#</a><a id="overload3"></a><a id="overload-arg-s-is-invalid"></a>overload arg &#39;%s&#39; is invalid</dt>
<dd>

<p>(W) <code>use overload</code> was passed an argument it did not recognize. Did you mistype an operator?</p>

</dd>
</dl>

<h1 id="BUGS-AND-PITFALLS"><a class="permalink" href="overload.html#BUGS-AND-PITFALLS">#</a><a id="BUGS"></a>BUGS AND PITFALLS</h1>

<ul>

<li><p>A pitfall when fallback is TRUE and Perl resorts to a built-in implementation of an operator is that some operators have more than one semantic, for example <code>|</code>:</p>

<pre><code>use overload &#39;0+&#39; =&gt; sub { $_[0]-&gt;{n}; },
    fallback =&gt; 1;
my $x = bless { n =&gt; 4 }, &quot;main&quot;;
my $y = bless { n =&gt; 8 }, &quot;main&quot;;
print $x | $y, &quot;\n&quot;;</code></pre>

<p>You might expect this to output &quot;12&quot;. In fact, it prints &quot;&lt;&quot;: the ASCII result of treating &quot;|&quot; as a bitwise string operator - that is, the result of treating the operands as the strings &quot;4&quot; and &quot;8&quot; rather than numbers. The fact that numify (<code>0+</code>) is implemented but stringify (<code>&quot;&quot;</code>) isn&#39;t makes no difference since the latter is simply autogenerated from the former.</p>

<p>The only way to change this is to provide your own subroutine for <code>&#39;|&#39;</code>.</p>

</li>
<li><p>Magic autogeneration increases the potential for inadvertently creating self-referential structures. Currently Perl will not free self-referential structures until cycles are explicitly broken. For example,</p>

<pre><code>use overload &#39;+&#39; =&gt; &#39;add&#39;;
sub add { bless [ \$_[0], \$_[1] ] };</code></pre>

<p>is asking for trouble, since</p>

<pre><code>$obj += $y;</code></pre>

<p>will effectively become</p>

<pre><code>$obj = add($obj, $y, undef);</code></pre>

<p>with the same result as</p>

<pre><code>$obj = [\$obj, \$foo];</code></pre>

<p>Even if no <i>explicit</i> assignment-variants of operators are present in the script, they may be generated by the optimizer. For example,</p>

<pre><code>&quot;obj = $obj\n&quot;</code></pre>

<p>may be optimized to</p>

<pre><code>my $tmp = &#39;obj = &#39; . $obj;  $tmp .= &quot;\n&quot;;</code></pre>

</li>
<li><p>The symbol table is filled with names looking like line-noise.</p>

</li>
<li><p>This bug was fixed in Perl 5.18, but may still trip you up if you are using older versions:</p>

<p>For the purpose of inheritance every overloaded package behaves as if <code>fallback</code> is present (possibly undefined). This may create interesting effects if some package is not overloaded, but inherits from two overloaded packages.</p>

</li>
<li><p>Before Perl 5.14, the relation between overloading and tie()ing was broken. Overloading was triggered or not based on the <i>previous</i> class of the tie()d variable.</p>

<p>This happened because the presence of overloading was checked too early, before any tie()d access was attempted. If the class of the value FETCH()ed from the tied variable does not change, a simple workaround for code that is to run on older Perl versions is to access the value (via <code>() = $foo</code> or some such) immediately after tie()ing, so that after this call the <i>previous</i> class coincides with the current one.</p>

</li>
<li><p>Barewords are not covered by overloaded string constants.</p>

</li>
<li><p>The range operator <code>..</code> cannot be overloaded.</p>

</li>
</ul>


      </div>
      <div id="footer">
        <p>Perldoc Browser is maintained by Dan Book (<a href="https://metacpan.org/author/DBOOK">DBOOK</a>). Please contact him via the <a href="https://github.com/Grinnz/perldoc-browser/issues">GitHub issue tracker</a> or <a href="mailto:dbook@cpan.org">email</a> regarding any issues with the site itself, search, or rendering of documentation.</p>

<p>The Perl documentation is maintained by the Perl 5 Porters in the development of Perl. Please contact them via the <a href="https://github.com/Perl/perl5/issues">Perl issue tracker</a>, the <a href="https://lists.perl.org/list/perl5-porters.html">mailing list</a>, or <a href="https://kiwiirc.com/client/irc.perl.org/p5p">IRC</a> to report any issues with the contents or format of the documentation.</p>


      </div>
    </div>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.slim.min.js" integrity="sha512-/DXTXr6nQodMUiq+IUJYCt2PPOUjrHJ9wFrqpJ3XkgPNOZVfMok7cRw6CSxyCQxXn6ozlESsSh1/sMCTF1rL/g==" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.1/umd/popper.min.js" integrity="sha512-ubuT8Z88WxezgSqf3RLuNi5lmjstiJcyezx34yIU2gAHonIi27Na7atqzUZCOoY4CExaoFumzOsFQ2Ch+I/HCw==" crossorigin="anonymous"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js" integrity="sha384-B4gt1jrGC7Jh4AgTPSdUtOBvfO8shuf57BaghqFfPlYxofvL8/KUEfYiJOMMV+rV" crossorigin="anonymous"></script>
    <script src="../highlight.pack.js"></script>
    <script>hljs.highlightAll();</script>
  </body>
</html>
